<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item to="/home/product/spumanage"
        >商品管理</el-breadcrumb-item
      >
      <el-breadcrumb-item to="/home/product/brandmanage"
        >品牌管理</el-breadcrumb-item
      >
      <el-breadcrumb-item>添加品牌</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <div class="box">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <h3 style="line-height: 32px">
              <i class="el-icon-edit"></i> &nbsp; 内容信息
            </h3>
          </div>
        </el-col>
      </el-row>
      <div class="divider"></div>
      <el-row>
        <el-col :span="12">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="品牌名称" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
              <p class="beizhu">
                备注：英文标识，只允许含有：英文、数字、中划线
              </p>
            </el-form-item>
            <el-form-item label="品牌首字母" prop="pinyin">
              <el-input v-model="ruleForm.pinyin"></el-input>
            </el-form-item>
            <el-form-item label="品牌logo" prop="logo">
              <span class="beizhu"
                >备注：单图图片尺寸为：300*100，只能上传jpg/png文件，且大小不超过5MB</span
              >
              <!-- 隐藏域，提交上传的图片路径 -->
              <input type="hidden" v-model="ruleForm.logo" />
              <el-upload
                class="avatar-uploader"
                name="file"
                :data="{ brandNamePinyin: ruleForm.pinyin }"
                action="http://localhost:9060/upload/brand-logo"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="品牌简介" prop="description">
              <el-input
                type="textarea"
                rows="5"
                v-model="ruleForm.description"
              ></el-input>
            </el-form-item>
            <el-form-item label="关键词" prop="keywords">
              <el-input size="small" v-model="ruleForm.keywords"></el-input>
              <p class="beizhu">
                备注：关键词列表，输入多个关键词请以英文逗号进行分割
              </p>
            </el-form-item>
            <el-form-item label="排序值" prop="sort">
              <el-input v-model="ruleForm.sort"></el-input>
              <p class="beizhu">排序值越大越靠前</p>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >提交</el-button
              >
              <el-button @click="$router.go(-1)">返回</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "",                 // 表示上传图片的访问路径
      categoryId: 0,                // 表示选中的类别ID
      props: {
        lazy: true,                 // 懒加载
        emitPath: false,            // 设置 false，只返回该节点的值
        lazyLoad: (node, resolve) => {
          /** 定义懒加载方式 */
          console.log("选择的当前节点：", node);
          let parentId = 0;
          if (!node.root) {
            parentId = node.data.value;
          }
          this.$api.categoryApi
            .queryByParent({ parentId: parentId })
            .then((res) => {
              console.log("加载子类别：", res);
              if (res.data.state == 200) {
                // 整理数据结构, 返回类别数组 [{label:'类别名', value:'类别id'}...]
                let nodes = [];
                res.data.data.list.forEach((item) => {
                  nodes.push({
                    label: item.name,
                    value: item.id,
                    leaf: item.parent != 1,
                  });
                });
                resolve(nodes);
              } else {
                this.$alert(res.data.message, "提示");
              }
            });
        },
      },
      ruleForm: {                   // 绑定表单数据
        name: "",
        description: "",
        keywords: "",
        logo: "",
        pinyin: "",
        sort: "",
        enable: 1,
      },
      rules: {
        name: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
        pinyin: [
          { required: true, message: "请输入品牌首字母", trigger: "blur" },
        ],
        logo: [{ required: true, message: "请选择品牌logo", trigger: "blur" }],
        description: [
          { required: true, message: "请输入品牌简介", trigger: "blur" },
        ],
        keywords: [
          {
            required: true,
            message: "请输入关键词（多个关键词以英文逗号分隔）",
            trigger: "blur",
          },
        ],
      },
    };
  },

  methods: {
    /**
     * 处理上传成功
     */
    handleUploadSuccess(res, file) {
      console.log(res);
      this.ruleForm.logo = res.data.url;
      this.imageUrl = URL.createObjectURL(file.raw);
    },

    /**
     * 处理上传之前的图片格式验证
     */
    beforeUpload(file) {
      const isJPGPNG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPGPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isJPGPNG && isLt5M;
    },

    /** 提交表单 */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          // 新增品牌
          this.$api.brandApi.add(this.ruleForm).then((res) => {
            if (res.data.state == 200) {
              this.$message({
                showClose: true,
                message: "恭喜你，品牌添加成功",
                type: "success",
              });
              return this.$api.brandApi.rebuildCache()
            } else {
              this.$alert(res.data.message, "提示");
            }
          }).then(res=>{
            console.log('重建缓存完成', res)
            // 重建缓存完毕
            if(res.data.state == 200) {
              this.$router.push("/home/product/brandmanage");
            }else{
              this.$alert(res.data.message, "提示");
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
